package com.cpe.web.controller.appoint;

import static com.sql.data.domain.user.UserRespCode.INVALID_TOKEN;
import static com.sql.data.response.CommonRespCode.EXCEPTION;
import static org.springframework.web.bind.annotation.RequestMethod.GET;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.cpe.data.domain.appoint.Appoint;
import com.cpe.data.domain.member.Member;
import com.cpe.repository.mapper.appoint.AppointMapper;
import com.cpe.repository.mapper.member.MemberMapper;
import com.cpe.transfer.appoint.AppointTransfer;
import com.github.pagehelper.PageHelper;
import com.sql.data.request.BaseQuery;
import com.sql.data.response.JsonResponse;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequestMapping("/appoints")
public class AppointController {

	@Resource
	private AppointMapper appointMapper;

	@Resource
	private AppointTransfer appointTransfer;

	@Resource
	private MemberMapper memberMapper;

	/**
	 * 查询体质项目列表，并关联查询出该学生在该体质项目的的预约情况
	 */
	@RequestMapping(value = "/info_with_childs", method = GET)
	public JsonResponse getInfoWithChilds(BaseQuery query, HttpSession session, @RequestHeader String openid) {
		// 登录校验
		Member member = (Member) session.getAttribute("loginer");
		if (member == null) {
			// 尝试从Header里读取openid
			member = memberMapper.findByOpenid(openid);
			if (member == null) {
				return JsonResponse.custom(INVALID_TOKEN);
			}
		}

		try {
			// 进行分页查询
			PageHelper.startPage(query.pageWhitoutOrder());
			List<Appoint> appoints = appointMapper.findByAppointDeadLineGte(new Date());
			return JsonResponse.ok(appointTransfer.toPageInfo(appoints, member.getId()));
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return JsonResponse.custom(EXCEPTION);
		}
	}
}
